<template>
  <div class="hacevn">
    <el-button class="cheaback" type="text" icon="el-icon-back" @click="hback"
      >返回</el-button
    >
    <el-tabs title="发布文章">
      <!-- 发布文章的对话框 -->

      <el-form
        :model="pubForm"
        :rules="artkistVisibles"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="pubForm.title"
            placeholder="请输入标题"
            style="width: 50%"
             maxlength="40"
          ></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="text">
          <el-input
            v-model="pubForm.originalText"
            placeholder="副标题"
            style="width: 50%"
            maxlength="40"

          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="knowledgeType">
           <el-cascader
           v-model="info.value"
           :options="info"
           :props="{ expandTrigger: 'hover' }"
           @change="handleChange"></el-cascader>
        </el-form-item>
            <!-- 图片 -->
      <el-form-item label="文章头图" >
     <el-upload
 action=""
 :http-request="Upload"
 :data="Aliyun"
 :multiple="false"
 :show-file-list="true"
 list-type="picture-card"
 :on-preview="handlePictureCardPreview"
 :on-remove="handleRemove"
 :limit="1"
>
 <i class="el-icon-plus" />
</el-upload>
<el-dialog :visible.sync="dialogVisible">
 <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
    

        </el-form-item>
        <el-form-item label="文章内容" prop="detail">
          <!-- 使用 v-model 进行双向的数据绑定 -->
         
           <div class="aaa">
         <!-- 工具栏 -->

         <Toolbar
         
             :editor="editor"
             :defaultConfig="toolbarConfig"
         />
         <!-- 编辑器 -->
         <Editor
      
             :defaultConfig="editorConfig"
             v-model="html"
             @onChange="onChange"
             @onCreated="onCreated"
         />
     </div>
       
     
        </el-form-item>
        
        <el-row>
        <el-button class="chonegt" type="primary" id="upload" @click="hPub()">发布</el-button>
        </el-row>
      </el-form>
    </el-tabs>
  </div>
</template>

<script>
import { addfitment,addfit } from "@/api/roles";
// import { ossmessgtr,ossuploa } from '@/api/oss'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import ossUpload from '@/components/Hamburger/oss'
import {ossmessage,ossuploading} from '@/api/oss'
import { client } from '@/components/Hamburger/ossss'

// import { Quill } from 'vue-quill-editor'
// 	import { ImageExtend } from 'quill-image-extend-module'
	// Quill.register('modules/ImageExtend', ImageExtend)


export default {
components: { Editor, Toolbar },//组件引入

  data() {
    return {
      toolbarConfig:'',
     
  	 		editor: null, //实例
                editorConfig: {
               placeholder: '请输入内容...',

      MENU_CONF: {
            uploadImage: {
                customUpload:    //自定义上-oss
                    async (file, insertFn) => {
                        const resultUrl = await ossUpload(file, file.name)
                        insertFn(resultUrl)
                    }
                   }
               }

           },
           IA_inputw:'',
     html:'',
      file:'',
      category:'',
      resultGTR:'',
      capture:'',
     dialogImageUrl:'',
     dialogVisible:false,
     Aliyun: {},
     imgUrl:[],
     list:[],
     info:[],
      pubForm: {
        richTextContent:'',
        originalText:'',
        title: "",
        category: {
         channel: "string",
         type: "string"
  },
        detail:'',
        images:[],
        text: '',
      },
      artkistVisibles: {
        title: [
          {
            required: true,
            message: "请输入文章标题",
            trigger: "blur",
          },
          {
            min: 1,
            max: 40,
            message: "文章标题的长度为1-40个字符",
            trigger: "blur",
          },
        ],
        originalText:[
             {
            required: true,
            message: "请输入福标题",
            trigger: "blur",
          },
        ],
        cate_id: [
          {
            required: true,
            message: "请选择文章标题",
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: "请输入文章内容",
            trigger: "blur",
          },
        ],
        cover_img: [
          {
            required: true,
            message: "请选择文章封面",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created(){
    this.loavhenge()
    this.loadefc()
  },
  methods: {
   async loavhenge(){
    const { data } = await ossmessage({
        'ossGroup':'CommodityMainImages'
      })
          this.Aliyun = data
     
    },
   async loadefc(){
        // 渲染分类
       const ress = await addfit()
        //  console.log('74',ress.data);
         this.list = JSON.parse(ress.data)
        //  console.log('74',this.list);
         for(let i =0; i < this.list.length; i++){
           this.info.push({label:this.list[i].name,value:this.list[i].data[0].data[0].category.channel})
           this.info[i].children=[]
          //  console.log(this.info);
           if(this.list[i].data[0].data.length>0){
             for(let j = 0; j < this.list[i].data[0].data.length; j++){
               this.info[i].children.push({label:this.list[i].data[0].data[j].name,value:this.list[i].data[0].data[j].category.type})
              // console.log('741');
            }
              }
          
         }
    },
    handleChange(value){
      this.pubForm.category.channel = value[0]
      this.pubForm.category.type = value[1]
      console.log(this.pubForm.category.type);
    },
    // 头图
    Upload(file) {
   const that = this
   // 判断扩展名
   const tmpcnt = file.file.name.lastIndexOf('.')
   const exname = file.file.name.substring(tmpcnt + 1)
   const names = ['jpg', 'jpeg', 'png','webP']
   if (names.indexOf(exname) < 0) {
    this.$message.error('不支持的格式!')
    return
   }
   if (file.size > 1024 * 1024) {
    this.$message.error('图片大小最大1M')
    return
   }
  
   async function multipartUpload() {
    const listdata = await ossuploading({
      'fileName':'.jpg','ossGroup':'CommodityMainImages'
    })
     let fileName = listdata.data.path
    //  console.log('741',fileName);
    //  console.log('999',file);
    client(that.Aliyun).put(fileName, file.file,
     {
      progress: function(p) { // 获取进度条的值
      //  console.log('777',p)
       that.progress = p * 100
      }
     }).then(
     result => {
      // 下面是如果对返回结果再进行处理，根据项目需要
      // console.log(result)
      // that.imgUrl = 'http://' + result.bucket + '.' + that.Aliyun.endpoint + '/' + result.name
      that.dialogImageUrl = result.url
        // console.log('444',that.dialogImageUrl)
      that.imgUrl.push({
       name: file.file.name,
       url: result.url
      })
      // that.pubForm.images.push(that.dialogImageUrl)
      // console.log('789',that.pubForm.images);
     })
   }
   multipartUpload()
  },
  // 图片预览
  handlePictureCardPreview(file) {
   this.dialogImageUrl = file.url
   this.dialogVisible = true
  },
    // 删除图片
  handleRemove(file, fileList) {
   // console.log(file)
   for (var i in this.imgUrl) {
    if (this.imgUrl[i].name === file.name) {
     this.imgUrl.splice(i, 1)
    }
   }
      // console.log('789w',this.pubForm.images);

  },
  //  上传
     onCreated(editor) {
   			          this.editor = Object.seal(editor) 
     			        },
   			        onChange(editor) {
   			        },
    // 提交
    hPub() {
         this.pubForm.richTextContent = this.html
         for (let i = 0; i < this.imgUrl.length; i++) {
          this.pubForm.images.push(this.imgUrl[i].url)
        }
      setTimeout(async() => {
                  
           this.html = this.html.replace(/<img/gi,
          '<img style="max-width:100%; height:auto;display:inline-block;"')
          // // console.log('777',this.html);

      this.$refs.pubFormRef.validate(async (valid) => {
        if(!valid) return
      //  this.pubForm.detail = this.html
      // this.pubForm.text = this.html
      this.pubForm.text = `<html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico"><title>${this.pubForm.title}</title></head>
     <body style="margin:0">
       <div>
     <p>
    <img style='max-width:100%;height:auto;display:inline-block;margin:0px auto;' 
    src=${this.pubForm.images}
   />
     </p>
    </div>
   <div style="background-color:#fff; height:70%;padding:1px 10px 10px 10px;
    border-radius:20px 20px 0 0;position: relative; bottom: 25px;">
   ${this.html}</div>
          <div class="blackScreen" style="display: none;display:none;    position:fixed;    top:0;    right:0;    bottom:0;    left:0;    background-color:#000000;    z-index:1000;">"
            <span class="fullScreenImg" style='position:absolute;    top:0;    right:0;    bottom:60px;    left:0;    background:center center no-repeat;    background-size:contain;'></span>" 
        </div>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"><\/script>

    <script>
        $(document).ready(function () {
    $("body").append("" );
});
 
$(function () {
  
// 放大图片 

    $('img').on('click', function () {
        // console.log("放大");
        if (this.getAttribute("src")) {
             $(".fullScreenImg").css('background-image', 'url(\\\'' + this.getAttribute('src') + '\\\')');
            $(".blackScreen").fadeIn(100);
        }
    });
  
// 关闭放大图片
    $(".blackScreen").on("click", function () {
        // console.log("关闭");
        $(".blackScreen").fadeOut(100);
    });
 
});
    <\/script>
   </body></html>`
  //  富文本结束
      const res = await addfitment(this.pubForm); 
      this.$message.success(res.msg)
      if(res.code == 200){
        this.$router.push('/home/fitments/knowledge')
      } else return

      })
      // console.log(res);
    },1000)
    },
      //返回
    hback() {
      this.$router.back();
    },
  },
     beforeDestroy() { //销毁组件
   		        if (this.editor == null) return
   		        this.editor.destroy() // 组件销毁时，及时销毁编辑器
   	     }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
.el-form{
  line-height: 160px;
}
.hacevn {
  background-color: #fff;
  padding: 20px;
}
.chonegt {
  transform: translateX(140%);
  color: #fff;
  
  background-color: #ff7144;
  border: 1px solid #fff;
}
.escanut {
  width: 70%;
  height: 70%;
}
::v-deep .ql-editor {
  height: 300px;
}
.aaa{
  width: 80%;
}

</style>
